﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EventScavenger
{
    public partial class ReaperServiceEdit : Form
    {
        public ReaperServiceEdit()
        {
            InitializeComponent();
        }

        private EventScavengerDAL eventScavengerDAL;

        public Reaper SelectedService { get; set; }

        public DialogResult Show(EventScavengerDAL eventScavengerDAL)
        {
            this.eventScavengerDAL = eventScavengerDAL;
            return ShowDialog();
        }

        private void ReaperServiceEdit_Load(object sender, EventArgs e)
        {
            LoadCollectors();
            if (SelectedService != null)
            {
                txtServer.Text = SelectedService.ServerName;
            }
        }

        private void timerServiceRegistrationHelpUpdate_Tick(object sender, EventArgs e)
        {
            timerServiceRegistrationHelpUpdate.Enabled = false;

            string helpText = "The following is simply to help you set up an instance of Event Reaper Service.\r\n";
            helpText += "1. Copy EventReaper.exe and EventReaper.exe.config to a new directory\r\n";
            helpText += "2. Open an Administrative command window (cmd.exe)\r\n";
            helpText += string.Format("3. Run EventReaper.exe -install \"{0}\" \"{0}\"\r\n", txtServiceName.Text);
            helpText += string.Format("4. Edit EventReaper.exe.config and set collector name e.g:\r\n" +
                        "\t<setting name=\"ColletorName\" serializeAs=\"String\">\r\n" +
                        "\t\t<value>{0}</value>\r\n" +
                        "\t</setting>\r\n", cboCollector.Text);
            helpText += string.Format("5. To uninstall run: EventReaper.exe -uninstall \"{0}\"\r\n", txtServiceName.Text);

            txtServiceRegistration.Text = helpText;
        }

        private void txtServiceName_TextChanged(object sender, EventArgs e)
        {
            timerServiceRegistrationHelpUpdate.Enabled = false;
            timerServiceRegistrationHelpUpdate.Enabled = true;
        }

        private void cmdTest_Click(object sender, EventArgs e)
        {
            if (TestServiceExistance(txtServer.Text, txtServiceName.Text, false))
            {
                MessageBox.Show("Success!\r\nService can be accessed", "Service", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void cmdOK_Click(object sender, EventArgs e)
        {
            if (txtServer.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must specify a server name", "Server name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtServer.Focus();
            }
            else if (cboCollector.SelectedIndex == -1)
            {
                MessageBox.Show("You must choose a collector", "Collector", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cboCollector.Focus();
            }
            else if (txtServiceName.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must specify a service name", "Service name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtServiceName.Focus();
            }
            else if (!chkEnabled.Checked || TestServiceExistance(txtServer.Text, txtServiceName.Text))
            {
                
                if (SelectedService == null)
                {
                    

                    SelectedService = new Reaper()
                    {
                        ReaperId = 0,  
                        ServerName = txtServer.Text
                    };
                }
                else
                {
                    SelectedService.ServerName = txtServer.Text;
                }
                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
        }

        private void LoadCollectors()
        {
            try
            {
                List<Collector> collectors = eventScavengerDAL.GetCollectorList();
                foreach (Collector collector in collectors)
                {
                    cboCollector.Items.Add(collector);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private bool TestServiceExistance(string serverName, string serviceName, bool allowContinue = true)
        {
            bool ignoreError = false;
            try
            {
                System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceName, serverName);
                string s = sc.ServiceName;
                ignoreError = true;
            }
            catch (Exception ex)        
            {
                if (allowContinue && MessageBox.Show("The specified service does not exist yet or cannot be accessed!\r\nContinue anyway?\r\nDetails:\r\n  " +
                        ex.Message.Replace("\r\n", "  \r\n"), "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.Yes)
                {
                    ignoreError = true;
                }
                else
                {
                    MessageBox.Show("The specified service does not exist yet or cannot be accessed!\r\nDetails:\r\n  " +
                        ex.Message.Replace("\r\n", "  \r\n"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return ignoreError;
        }


    }
}
